<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :modal="true"
      :appendToBody="true"
      width="800px"
      v-dialog-drag
      :close-on-click-modal="false"
      top="5vh"
      @close="handleClose()"
      @open="handleOpen()"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        :disabled="!canEdit"
        v-loading="loading"
      >
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="任务模板名称" prop="taskTemplateName">
              <el-input
                type="text"
                v-model="form.taskTemplateName"
                placeholder="请输入任务模板名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联总部模板" prop="parentTaskTemplateCode">
              <el-select
                v-model="form.parentTaskTemplateCode"
                size="small"
                filterable
                clearable
                :disabled="!!row"
                placeholder="请选择总部模板"
                @change="handleParentTaskTemplateChange"
              >
                <el-option
                  v-for="item in parentTaskTemplateOptions"
                  :key="item.taskTemplateCode"
                  :label="item.taskTemplateName"
                  :value="item.taskTemplateCode"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="任务类型" prop="taskType">
              <el-select
                v-model="form.taskType"
                size="small"
                placeholder="请选择任务类型"
                :disabled="!!form.parentTaskTemplateCode"
                @change="handleTaskTypeChange"
              >
                <el-option
                  v-for="item in dict.taskType"
                  :key="item.codevalue"
                  :label="item.codename"
                  :value="item.codevalue"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否品控关注" prop="isConcernedTask">
              <!-- 当任务类型选择“头班首检任务、跟班巡检任务、品控校准任务”这3个品控任务时，不可修改 -->
              <el-radio-group
                v-model="form.isConcernedTask"
                :disabled="
                  !!form.parentTaskTemplateCode ||
                  ['6', '7', '10'].includes(form.taskType)
                "
              >
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="关联设备分类" prop="associatedDeviceCategory">
              <el-select
                v-model="form.associatedDeviceCategory"
                size="small"
                placeholder="请选择设备分类"
                :disabled="!!form.parentTaskTemplateCode"
                clearable
                @change="handleAssociatedDeviceCategoryChange"
              >
                <el-option
                  v-for="item in dict.equipSortcode"
                  :key="item.codevalue"
                  :label="item.codename"
                  :value="item.codevalue"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 仅当“关联设备分类”有值时，显示“关联设备”字段 -->
          <el-col :span="12" v-if="form.associatedDeviceCategory">
            <el-form-item label="关联设备" prop="associatedDeviceName">
              <el-input
                type="text"
                v-model="form.associatedDeviceName"
                readonly
                placeholder="请选择设备"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="handleOpenEquipList"
                ></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                v-model="form.remark"
                :rows="3"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          v-if="canEdit"
          type="primary"
          :loading="saveloading"
          @click="handleSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 设备列表 -->
    <EquipList
      :visible.sync="equipListDialog.visible"
      :defaultValues="equipListDialog.defaultValues"
      :defaultSearch="{
        sortcode: form.associatedDeviceCategory,
      }"
      rowKey="equipId"
      :multiple="false"
      @closeDialog="handleEquipListClose"
    ></EquipList>
  </div>
</template>
<script>
import { checkPermi } from "@/utils/permission";
import {
  getTaskTemplateDetail,
  getTaskTemplateList,
  saveTaskTemplate,
} from "@/api/taskMgmt/template";
import EquipList from "@/views/components/equipList";
export default {
  components: { EquipList },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    row: {
      type: Object,
      default: null,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  dicts: ["equipSortcode", "taskType"],
  data() {
    return {
      loading: false,
      form: {
        taskTemplateName: null,
        parentTaskTemplateCode: null,
        taskType: null,
        isConcernedTask: "1",
        associatedDeviceCategory: null,
        associatedDevice: null,
        associatedDeviceName: null,
        remark: null,
        renderingMode: null,
      },
      rules: {
        taskTemplateName: [
          { required: true, message: "请输入任务模板名称", trigger: "change" },
          { max: 30, message: "任务名称长度最多30个字符", trigger: "change" },
        ],
        taskType: [
          { required: true, message: "请选择任务类型", trigger: "change" },
        ],
        isConcernedTask: [
          { required: true, message: "请选择是否品控关注", trigger: "change" },
        ],
        associatedDeviceName: [
          { required: true, message: "请选择关联设备", trigger: "change" },
        ],
        remark: [
          { max: 200, message: "备注长度最多200个字符", trigger: "change" },
        ],
      },
      parentTaskTemplateOptions: [],
      associatedDeviceOptions: [],
      saveloading: false,
      // 设备选择弹框
      equipListDialog: {
        visible: false,
        defaultValues: [],
      },
    };
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val);
      },
      get() {
        return this.visible;
      },
    },
    title() {
      if (this.disabled == true) {
        return "任务模板详情";
      }
      if (!!this.row) {
        return "编辑任务模板";
      }
      return "新增任务模板";
    },
    canEdit() {
      if (this.disabled == true) {
        return false;
      }
      if (this.row?.id) {
        return checkPermi(["taskMgmt:template:edit"]);
      }
      return true;
    },
  },
  methods: {
    handleClose() {
      this.$refs.ruleForm.resetFields();
    },
    handleOpen() {
      this.getDetails();
      this.getParentTaskTemplateOptions();
    },
    getDetails() {
      if (!this.row?.id) {
        return;
      }
      this.loading = true;
      getTaskTemplateDetail(this.row.id)
        .then((res) => {
          const {
            taskTemplateName,
            parentTaskTemplateCode,
            taskType,
            isConcernedTask,
            associatedDeviceCategory,
            associatedDevice,
            associatedDeviceName,
            remark,
            renderingMode,
          } = res.data;
          this.form = {
            taskTemplateName,
            parentTaskTemplateCode,
            taskType,
            isConcernedTask: isConcernedTask || "1",
            associatedDeviceCategory,
            associatedDevice,
            associatedDeviceName,
            remark,
            renderingMode,
          };
          this.loading = false;
        })
        .catch(() => {
          this.form = {
            taskTemplateName: null,
            parentTaskTemplateCode: null,
            taskType: null,
            isConcernedTask: "1",
            associatedDeviceCategory: null,
            associatedDevice: null,
            associatedDeviceName: null,
            remark: null,
          };
          this.loading = false;
        });
    },
    getParentTaskTemplateOptions() {
      const params = {
        query: {
          templateName: "",
          taskType: "",
          status: "1",
          templateCategory: "base", //总部侧模板列表，固定分类base
        },
      };
      getTaskTemplateList(params)
        .then((res) => {
          this.parentTaskTemplateOptions = res.rows;
        })
        .catch(() => {
          this.parentTaskTemplateOptions = [];
        });
    },
    handleParentTaskTemplateChange(value) {
      if (value) {
        const item = this.parentTaskTemplateOptions.find(
          (ele) => ele.taskTemplateCode == value
        );
        if (!item) {
          return;
        }
        // 选择了总部模板，回填任务类型、是否品控关注、关联设备分类、表单样式
        this.form.taskType = item.taskType;
        this.form.isConcernedTask = item.isConcernedTask;
        this.form.associatedDeviceCategory = item.associatedDeviceCategory;
        this.form.renderingMode = item.renderingMode;
      }
    },
    handleTaskTypeChange(value) {
      // 当任务类型选择“头班首检任务、跟班巡检任务、品控校准任务”这3个品控任务时，默认选中“是”，不可修改
      if (value == "7" || value == "10" || value == "6") {
        this.form.isConcernedTask = "1";
      }
      // 表单样式默认为1
      this.form.renderingMode = "1";
    },
    handleAssociatedDeviceCategoryChange() {
      this.form.associatedDevice = "";
      this.form.associatedDeviceName = "";
    },
    // 打开设备列表
    handleOpenEquipList() {
      const { associatedDevice, associatedDeviceName } = this.form;
      if (associatedDevice) {
        this.equipListDialog.defaultValues = [
          {
            equipId: associatedDevice,
            equipName: associatedDeviceName,
          },
        ];
      } else {
        this.equipListDialog.defaultValues = [];
      }
      this.equipListDialog.visible = true;
    },
    // 关闭设备列表
    handleEquipListClose(list) {
      if (!list?.length) {
        this.form.associatedDevice = null;
        this.form.associatedDeviceName = null;
      }
      this.form.associatedDevice = list[0].equipId;
      this.form.associatedDeviceName = list[0].equipName;
    },
    handleSubmit() {
      this.$refs.ruleForm.validate((flag) => {
        if (flag) {
          const {
            taskTemplateName,
            parentTaskTemplateCode,
            taskType,
            isConcernedTask,
            associatedDeviceCategory,
            associatedDevice,
            remark,
            renderingMode,
          } = this.form;
          const param = {
            id: this.row?.id || undefined,
            taskTemplateName,
            taskFormName: taskTemplateName, //默认为模板名称，表单设计时可改
            parentTaskTemplateCode,
            taskType,
            isConcernedTask,
            templateCategory: "custom", //工厂侧模板类型
            status: this.row?.id ? this.row.status : "0", //新增时，模板状态默认为“已停用”
            associatedDeviceCategory,
            associatedDevice,
            remark,
            renderingMode: renderingMode || "1",
          };
          saveTaskTemplate(param).then((res) => {
            this.msgSuccess("保存成功！");
            this.$emit("refresh");
            this.dialogVisible = false;
          });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.el-select {
  width: 100%;
}
</style>
